import React from 'react'
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import Cloud from 'leancloud-storage'
import './index.less'
function getBase64(img, callback) { //将文件对象转换为base64编码字符串
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) { //限制文件类型、文件大小
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

class ImgUpload extends React.Component {
  // 定义响应式数据的简写方法
  state = {
    loading: false,
  };

  // handleChange = info => {  //检测action地址上传图片的实时状态
  //   if (info.file.status === 'uploading') {
  //     this.setState({ loading: true });
  //     return;
  //   }
  //   if (info.file.status === 'done') {  //图片上传成功
  //     // Get this url from response in real world.
  //     getBase64(info.file.originFileObj, imageUrl =>{
  //         console.log(imageUrl)
  //         this.setState({
  //           imageUrl,
  //           loading: false,
  //         })
  //       },
  //     );
  //   }
  // };

  handleCustom = (info)=>{  //自定义图片上传
    // console.log(info);
    getBase64(info.file,(base64)=>{
      // console.log(base64);
      const file = new Cloud.File('poster.png', { base64 }); //构建leancloud文件对象
      file.save().then(res=>{ //保存图片
        console.log(res);
        let {url} = res.attributes
        this.setState({
          imageUrl:url,
          loading: false,
        })
        this.props.onChange(url)  //触发表单内部组件的value变化
      })
      
    })
  }

  render() {
    console.log('ImgUpload组件的props',this.props);
    const { loading, imageUrl } = this.state;
    let {value} = this.props //用户可能会提供的默认预览图
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <Upload
        name="avatar"
        listType="picture-card"
        className="img-uploader"
        showUploadList={false}
        beforeUpload={beforeUpload}
        customRequest={this.handleCustom}
      >
        {imageUrl || value ? <img src={imageUrl||value} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>
    );
  }
}

export default ImgUpload